package net.stogi.unicore.beyond.io.client.input.integerfield;

import net.stogi.unicore.beyond.api.model.InputDefinition;
import net.stogi.unicore.beyond.io.client.input.core.InputField;

import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.google.gwt.user.client.ui.Widget;

public class IntegerInputField implements InputField {

	protected final NumberField field = new NumberField();

	protected InputDefinition inputDefinition;

	public IntegerInputField(InputDefinition inputDefinition) {
		this(inputDefinition.getInputType().getName());
		this.inputDefinition = inputDefinition;
		initField();
	}

	@SuppressWarnings("unused")
	private IntegerInputField() {}

	private IntegerInputField(String inputTypeName) {
		if (!"integerfield".equals(inputTypeName)) {
			throw new IllegalArgumentException("Input definition is not type of 'integerfield'");
		}
	}

	@Override
	public Widget asWidget() {
		return field;
	}

	@Override
	public String getValue() {
		String value = null;
		
		if (field.getValue() != null) {
			value = String.valueOf(field.getValue().intValue());
		}
		
		return value;
	}

	@Override
	public void setValue(String value) {
		field.setValue(Integer.parseInt(value));
	}

	private void initField() {
		field.setAllowDecimals(false);
		field.setFieldLabel(inputDefinition.getName());
		field.setAllowBlank(Boolean.parseBoolean(inputDefinition.getProperty("empty").getValue()));
		if (inputDefinition.getProperty("max").getValue() != null) {
			field.setMaxValue(Integer.parseInt(inputDefinition.getProperty("max").getValue()));
		}
		if (inputDefinition.getProperty("min").getValue() != null) {
			field.setMinValue(Integer.parseInt(inputDefinition.getProperty("min").getValue()));
		}
	}

	@Override
	public void setError(String error) {
		if (error != null) {
			field.forceInvalid(error);
		}
		else {
			field.clearInvalid();
		}
	}
}
